package com.finalterm.user.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.finalterm.common.result.Result;
import com.finalterm.user.dto.UserLoginDTO;
import com.finalterm.user.dto.UserRegisterDTO;
import com.finalterm.user.handler.CustomBlockHandler;
import com.finalterm.user.service.UserService;
import com.finalterm.user.vo.LoginVO;
import com.finalterm.user.vo.UserVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
public class UserController {
    
    private final UserService userService;
    
    /**
     * 用户注册
     */
    @PostMapping("/register")

    public Result<UserVO> register(@Validated @RequestBody UserRegisterDTO registerDTO) {
        UserVO userVO = userService.register(registerDTO);
        return Result.success("注册成功", userVO);
    }
    
    /**
     * 用户登录
     */
    @PostMapping("/login")

    public Result<LoginVO> login(@Validated @RequestBody UserLoginDTO loginDTO) {
        LoginVO loginVO = userService.login(loginDTO);
        return Result.success("登录成功", loginVO);
    }
    
    /**
     * 获取用户信息
     */
    @GetMapping("/info/{userId}")
    @SentinelResource(value = "info",
            blockHandler = "handleException",
            blockHandlerClass = CustomBlockHandler.class)
    public Result<UserVO> getUserInfo(@PathVariable Long userId) {
        UserVO userVO = userService.getUserById(userId);
        return Result.success(userVO);
    }

    
    /**
     * 验证用户是否有效（内部调用）
     */
    @GetMapping("/validate/{userId}")
    public Result<Boolean> validateUser(@PathVariable Long userId) {
        boolean isValid = userService.validateUser(userId);
        return Result.success(isValid);
    }

    /**
     * 验证用户是否有效（模拟超时 - 测试用）
     */
    @GetMapping("/validate/slow/{userId}")
    @SentinelResource(value = "validateUserSlow", blockHandler = "getValidateUserSlowBlockHandler")
    public Result<Boolean> validateUserSlow(@PathVariable Long userId) {
        try {
            // 模拟处理时间超过Feign超时时间
            Thread.sleep(5000); // 5秒延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        boolean isValid = userService.validateUser(userId);
        return Result.success(isValid);
    }

    public Result<Boolean> getValidateUserSlowBlockHandler(Long userId, BlockException ex) {
        log.warn("用户验证触发Sentinel规则降级，userId: {}, 规则类型: {}, 异常: {}",
                userId, ex.getClass().getSimpleName(), ex.getMessage());
        return Result.error("系统熔断机制触发，接口超时，用户验证失败");
    }
}
